//
//  DCLoginViewController.m
//  Driver
//
//  Created by 大橙子 on 2018/11/5.
//  Copyright © 2018 Tomous. All rights reserved.
//

#import "DCLoginViewController.h"
#import "DCTabBarViewController.h"
@interface DCLoginViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) DCImageAndTextField *telTextField;
@property (nonatomic,strong) DCImageAndTextField *numTextField;
@end

@implementation DCLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpMainView];
}
-(void)setUpMainView
{
    UIImageView *backImageView = [[UIImageView alloc]initWithImage:IMAGENAME(@"login_backImg")];
    backImageView.frame = self.view.bounds;
    backImageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backImageView];
    
    //毛玻璃
//    UIBlurEffect *blurEffect =[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//    UIVisualEffectView *effectView =[[UIVisualEffectView alloc]initWithEffect:blurEffect];
//    effectView.frame = self.view.bounds;
//    [self.view addSubview:effectView];
    
    
    
    UIImageView *logoImage = [[UIImageView alloc]initWithImage:IMAGENAME(@"login_logo")];
    logoImage.frame = CGRectMake(0, 0, ScreenWidth, 300*HEIGHTSCALE6);
    [self.view addSubview:logoImage];
    
    CGFloat kMargin = 30*WIDTHSCALE6;
    CGFloat fieldHeight = 45;
    
    /*
     手机号
     */
    DCImageAndTextField *telTextField = [[DCImageAndTextField alloc]initWithFrame:CGRectMake(kMargin, ScreenHeight/2+10, ScreenWidth - kMargin*2, fieldHeight)];
    telTextField.line.hidden = YES;
    telTextField.imageView.image = IMAGENAME(@"账号");
    telTextField.backgroundColor = [UIColor whiteColor];
    telTextField.textField.placeholder = @"输入手机号";
    telTextField.textField.textColor = DCColor(164, 164, 164);
    //    telTextField.text = @"18910613868";
//    telTextField.textField.text = @"15012345678";
    telTextField.textField.text = [DCTool getKeychainDataForKey:@"userName"];
    telTextField.textField.delegate = self;
    telTextField.textField.keyboardType = UIKeyboardTypeNumberPad;
    telTextField.textField.font = FONT(17);
    telTextField.textField.returnKeyType = UIReturnKeyGo;
    telTextField.textField.rightViewMode = UITextFieldViewModeAlways;
    self.telTextField = telTextField;
    [self.view addSubview:telTextField];
    
    /*
      验证码按钮
     */
    UIView *codeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, telTextField.height)];
    codeView.backgroundColor = [UIColor whiteColor];
    telTextField.textField.rightView = codeView;
    
    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(0, 5, codeView.width - 10, codeView.height - 10);
    codeBtn.backgroundColor = BlueColor;
    [codeBtn setTitle:@"验证" forState:UIControlStateNormal];
    [codeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    codeBtn.tag = 2;
    codeBtn.layer.cornerRadius = 4;
    codeBtn.clipsToBounds = YES;
    [codeBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [codeView addSubview:codeBtn];
    
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(telTextField.x, telTextField.bottom, telTextField.width, 1)];
    line.backgroundColor = [UIColor lightGrayColor];
    line.alpha = 0.8;
    [self.view addSubview:line];
    
    /*
     验证码
     */
    DCImageAndTextField *numTextField = [[DCImageAndTextField alloc]initWithFrame:CGRectMake(telTextField.x, CGRectGetMaxY(line.frame), telTextField.width+2.5, telTextField.height)];
    numTextField.line.hidden = YES;
    numTextField.imageView.image = IMAGENAME(@"密码");
    numTextField.backgroundColor = [UIColor whiteColor];
    numTextField.textField.placeholder = @"验证码";
    numTextField.textField.textColor = DCColor(164, 164, 164);
    numTextField.textField.text = @"123456";
    numTextField.textField.delegate = self;
    numTextField.textField.returnKeyType = UIReturnKeyGo;
    numTextField.textField.keyboardType = UIKeyboardTypeNumberPad;
    numTextField.textField.font = FONT(17);
    self.numTextField = numTextField;
    [self.view addSubview:numTextField];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(numTextField.x, numTextField.bottom, numTextField.width, 1)];
    line1.backgroundColor = [UIColor lightGrayColor];
    line1.alpha = 0.8;
    [self.view addSubview:line1];
    /*
     登录
     */
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(telTextField.x, CGRectGetMaxY(numTextField.frame)+15, (telTextField.width - 10)/2, 50);
    loginBtn.backgroundColor = BlueColor;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.layer.cornerRadius = 24;
    loginBtn.clipsToBounds = YES;
    loginBtn.tag = 0;
    [loginBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    /*
     重置
     */
    UIButton *resetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    resetBtn.frame = CGRectMake(CGRectGetMaxX(loginBtn.frame)+10, loginBtn.y, loginBtn.width, loginBtn.height);
    resetBtn.backgroundColor = BlueColor;
    [resetBtn setTitle:@"重置" forState:UIControlStateNormal];
    resetBtn.layer.cornerRadius = 24;
    resetBtn.clipsToBounds = YES;
    resetBtn.tag = 1;
    [resetBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:resetBtn];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, ScreenHeight - bottomSafeHeight - 40, self.view.width, 30)];
    label.text = [NSString stringWithFormat:@"司机端 V%@",DEVICE_APP_VERSION];
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
}
-(void)btnDidClick:(UIButton *)btn
{
    if (btn.tag == 0) {
        DCLog(@"登录");
        [self loginBtnDidClick];
    }else if(btn.tag == 1){
        self.telTextField.textField.text = nil;
        self.numTextField.textField.text = nil;
        [self.telTextField becomeFirstResponder];
    }else{
        DCLog(@"获取验证码");
        [DCTool startTimeWithButton:btn];
    }
}
/**
 点击登录
 */
-(void)loginBtnDidClick
{
    if (self.telTextField.textField.text.length == 0) {
        [self showMessage:@"请输入手机号" afterDelay:1.0];
        return;
    }
    if (self.telTextField.textField.text.length != 11) {
        [self showMessage:@"请输入正确的手机号" afterDelay:1.0];
        return;
    }
    if (self.numTextField.textField.text.length == 0) {
        [self showMessage:@"请输入密码" afterDelay:1.0];
        return;
    }
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"username"] = self.telTextField.textField.text;
    info[@"password"] = self.numTextField.textField.text;
    info[@"loginType"] = @"004";
//    info[@"smsCodeAuth"] = @(self.loginType);
    info[@"osType"] = @"iOS";
    __weak typeof(self) weakself = self;
    [self postWithURL:Login_URL withAleartMessage:@"登录中..." withDictionary:info success:^(id responseObject) {

        UserInfo *user = [UserInfo shareInstance];
        user = [UserInfo mj_objectWithKeyValues:responseObject];
        DCLog(@"responseObject---%@",responseObject);
        /*
         保存用户账号
         */
        [DCTool addKeychainData:weakself.telTextField.textField.text forKey:@"userName"];

        //登录成功保存用户信息
        [user saveUserInfoToSanbox];

        //跳转
        DCTabBarViewController *tabBar = [[DCTabBarViewController alloc]init];
        [weakself presentViewController:tabBar animated:NO completion:nil];

    } failure:^(NSError *error) {

    }];
}
-(void)postWithURL:(NSString *)url withAleartMessage:(NSString *)message withDictionary:(NSMutableDictionary *)dict  success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];//可以设置hud小方框透明背景
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];//用户不可以操作，透明背景
    [SVProgressHUD setBackgroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:message];
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.validatesDomainName = NO;
    securityPolicy.allowInvalidCertificates = YES;
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.securityPolicy = securityPolicy;
    [sessionManager POST:url parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            
            if (success) {
                success(responseObject);
            }
            [SVProgressHUD dismiss];
        }else{
            
            [SVProgressHUD showWithStatus:responseObject[@"msg"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
